package com.boot.mongodb.dao.impl;

import com.boot.mongodb.dao.UserDao;
import com.boot.mongodb.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserDaoImpl implements UserDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(User user) {
        this.mongoTemplate.save(user);
    }

    @Override
    public User getUser(String id) {
        Query query = new Query().addCriteria(Criteria.where("_id").is(id));
        return this.mongoTemplate.findOne(query,User.class);
    }

    @Override
    public List<User> getUsers() {
        return this.mongoTemplate.findAll(User.class);
    }

    @Override
    public List<User> getUserForPage(int pageNum, int pageSize) {
        if(pageNum <= 0){
            pageNum = 1;
        }
        if(pageSize <= 0){
            pageSize = 10;
        }
        Query query = new Query().skip((pageNum - 1) * pageSize)
                .limit(pageSize);
        return this.mongoTemplate.find(query, User.class);
    }

    @Override
    public void delete(String id) {
        Query query = new Query().addCriteria(Criteria.where("_id").is(id));
        this.mongoTemplate.remove(query, User.class);
    }

    @Override
    public void deletes(String[] ids) {
        Query query = new Query().addCriteria(Criteria.where("_id").in(ids));
        this.mongoTemplate.remove(query, User.class);
    }
}
